< previous page page_459 next page >

Page 459
For example, run Notepad and you will see that the initial caption of the Notepad window is Untitled Notepad. To find this window, you could call FindWindow as follows:
hwndNotepad = FindWindow(vbNullString, "Untitled - Notepad")
Notice that here you use only the window caption, sending the class name parameter a null string. However, suppose you saved or opened a file. Notepad's caption would change to reflect the new filename, so the preceding line of code would no longer successfully find the window. However, I happen to know that the name of the Windows Notepad class is Notepad, so I could use that instead:
hwndNotepad = FindWindow("Notepad", vbNullString)
tip.gif
Windows class names are not always this obvious; for example, one of the early Visual Basic form class names was ThunderForm. However, a Windows class spy utility, such as the one included with Visual C++, makes finding class names easy.

The preceding line of code can find the handle of the Notepad window no matter what the caption. This example works fine with one instance of Notepad, but what if multiple copies are running? The answer is to introduce a few more API calls: GetWindow, GetWindowText, and GetWindowClass.
Like FindWindow, GetWindow is used to return a window handle. However, rather than search by name, GetWindow finds windows based on their relationships to other windows. GetWindow can be used in a loop to browse through the entire window list, as shown in Listing 20.6. The code in this listing counts the number of instances of Notepad and prints the caption of each.
Listing 20.6 APIDEMO.ZIPFinding All the Notepad Windows
Public Const GW_HWNDFIRST = 0
Public Const GW_HWNDLAST = 1
Public Const GW_HWNDNEXT = 2
Public Const GW_HWNDPREV = 3
Public Const GW_OWNER = 4
Public Const GW_CHILD = 5
Public Const GW_MAX = 5

Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) _
                 As Long
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName _
                 As String, ByVal lpWindowName As String) As Long
Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd _
                 As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) _
                 As Long
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd _
                 As Long, ByVal lpString As String, ByVal cch As Long) As Long
continues

 
< previous page page_459 next page >